/**
 * 利用wait和notify成员进行线程同步的例程
 */
package thread;

public class J_WaitNotify {
    public static void main(String args[]) {
        J_Experiment5 data = new J_Experiment5();
        J_Assistant2 threadA = new J_Assistant2(data);
        J_Analyst2 threadB = new J_Analyst2(data);
        threadA.start();
        ;
        threadB.start();
        System.out.println("main方法结束");
    }
}

/**
 * 实验
 * */
class J_Experiment5 {
    //温度和气压
    private int m_temperature, m_pressure;
    private boolean m_ready = true;

    public synchronized void mb_update(int t, int p) {
        System.out.println("进入内部更新方法：");
        if (m_ready) {
            System.out.println("等到数据分析完成...");
            try {
                wait(); //等待数据分析
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("继续更新数据");
        }
        m_temperature = t;
        m_pressure = p;
        System.out.println("数据更新完成：温度为 " + t + "  气压为 " + p);
        m_ready = true;
        notify();
    }

    //数据分析
    public synchronized void mb_analyze() {
        System.out.println("进入数据分析方法内部：");
        if (!m_ready) {
            System.out.println("等待数据更新完成...");
            try {
                wait();//等待数据分析
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("继续分析数据");
        }

        int t = m_temperature;
        int p = m_pressure;
        System.out.printf("分析完成，温度(%1$d) 气压(%2$d)\r\n", t, p);
        m_ready = false;
        notify();
    }
}

/**
 * 实验室的助理人员
 * */
class J_Assistant2 extends Thread {
    J_Experiment5 m_data;

    public J_Assistant2(J_Experiment5 d) {
        m_data = d;
    }

    @Override
    public void run() {
        System.out.println("助理线程开始工作");
        int i, j;
        for (int k = 0; k < 3; k++) {
            i = (int) (Math.random() * 1000);
            j = (int) (Math.random() * 1000);
            m_data.mb_update(i, j);
        }
        System.out.println("助理线程结束工作");
    }
}

class J_Analyst2 extends Thread {
    J_Experiment5 m_data;

    public J_Analyst2(J_Experiment5 d) {
        m_data = d;
    }

    @Override
    public void run() {
        System.out.println("分析员线程开始工作");
        for (int i = 0; i < 3; i++) {
            m_data.mb_analyze();
        }
        System.out.println("分析员线程结束工作");
    }
}